package com.zbkj.crmeb.merchant.admin.controller;

import java.util.List;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.zbkj.crmeb.store.model.StoreCouponUserPhone;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.common.CommonPage;
import com.crmeb.core.common.CommonResult;
import com.common.PageParamRequest;
import com.github.pagehelper.util.StringUtil;
import com.zbkj.crmeb.enums.CouponUseTypeEnum;
import com.zbkj.crmeb.marketing.model.StoreCoupon;
import com.zbkj.crmeb.marketing.request.StoreCouponRequest;
import com.zbkj.crmeb.marketing.request.StoreCouponSearchRequest;
import com.zbkj.crmeb.marketing.service.StoreCouponService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;


/**
 * 优惠券配置
 * @author daigb
 * @date:  2022-01-17 13:51
 */
@RestController
@RequestMapping("api/admin/mer/marketing/coupon")
@Api(tags = "优惠券")
public class MerStoreCouponController extends AdminBaseController {
    @Autowired
    private StoreCouponService storeCouponService;

    /**
     * 新增
     * @param storeCouponRequest StoreCouponRequest 新增参数
     * @author Mr.Zhang
     * @since 2020-05-18
     */
    @ApiOperation(value = "新增")
    @PostMapping(value = "/save")
    public CommonResult<String> save(@RequestBody StoreCouponRequest storeCouponRequest, HttpServletRequest request){
    	storeCouponRequest.setMerId(getMerId(request));
    	
    	if(StringUtil.isEmpty(storeCouponRequest.getName())) {
    		return CommonResult.validateFailed("名字不能为空");
    	}
    	if(null == storeCouponRequest.getUseType()) {
    		return CommonResult.validateFailed("使用类型不能为空");
    	}
    	if(null == storeCouponRequest.getMoney()) {
    		return CommonResult.validateFailed("面值不能为空");
    	}
    	if(null == storeCouponRequest.getTotal() && Objects.equals(storeCouponRequest.getReleaseType(),1)) {
    		return CommonResult.validateFailed("发放总数不能为空");
    	}
    	if(CouponUseTypeEnum.CATE.getCode().equals(storeCouponRequest.getUseType())) {
    	    if (null == storeCouponRequest.getPrimaryKey()){
                return CommonResult.validateFailed("请选择商品/分类！");
            }
            String cateIds = storeCouponRequest.getPrimaryKey().getString("cateIds");
            List<String> tempIdsList = JSONObject.parseArray(storeCouponRequest.getPrimaryKey().getJSONArray("tempIds").toString(),String.class);
            //List<String> cateIdsList = JSONObject.parseArray(storeCouponRequest.getPrimaryKey().getJSONArray("cateIds").toString(),String.class);
            List<String> seasonsList = JSONObject.parseArray(storeCouponRequest.getPrimaryKey().getJSONArray("seasons").toString(),String.class);
            List<String> brandIdsList = JSONObject.parseArray(storeCouponRequest.getPrimaryKey().getJSONArray("brandIds").toString(),String.class);
            if (CollectionUtils.isEmpty(tempIdsList) && StringUtil.isEmpty(cateIds) && CollectionUtils.isEmpty(seasonsList) && CollectionUtils.isEmpty(brandIdsList)){
                return CommonResult.validateFailed("请选择商品/分类！");
            }
    	}
    	if(CouponUseTypeEnum.GOODS.getCode().equals(storeCouponRequest.getUseType()) && CollectionUtils.isEmpty(storeCouponRequest.getGoodsIds())) {
    		return CommonResult.validateFailed("请选择指定商品！");
    	}
        if(Objects.equals(storeCouponRequest.getType(),3)) {
            if (Objects.equals(storeCouponRequest.getReleaseType(),1)){
                return CommonResult.validateFailed("自动发放需要设置发放时间为按月/周发放");
            }
            if (Objects.isNull(storeCouponRequest.getReleaseDate())){
                return CommonResult.validateFailed("按月发放日期不能为空");
            }
        }
    	if(null == storeCouponRequest.getReceiveStartTime() && Objects.equals(storeCouponRequest.getReleaseType(),1)) {
    		return CommonResult.validateFailed("请设置领取开始时间");
    	}
    	if(null == storeCouponRequest.getReceiveEndTime() && Objects.equals(storeCouponRequest.getReleaseType(),1)) {
    		return CommonResult.validateFailed("请设置领取结束时间");
    	}

    	if(storeCouponRequest.getIsFixedTime() && (null == storeCouponRequest.getUseStartTime() || null == storeCouponRequest.getUseEndTime())) {
    		return CommonResult.validateFailed("请设置有效使用时间");
    	}
    	if(!storeCouponRequest.getIsFixedTime() && (null == storeCouponRequest.getDay() || null == storeCouponRequest.getLastDay())) {
    		return CommonResult.validateFailed("请设置有效天数");
    	}
    	if(storeCouponRequest.getReleaseType() == 1 && storeCouponRequest.getIsFixedTime() && storeCouponRequest.getReceiveEndTime().getTime() > storeCouponRequest.getUseEndTime().getTime()) {
    		return CommonResult.validateFailed("领取截止时间不能大于使用截止时间");
    	}
    	if(null == storeCouponRequest.getCrowd()) {
    		return CommonResult.validateFailed("请设置适用人群");
    	}

        if (5 == storeCouponRequest.getCrowd() && Objects.isNull(storeCouponRequest.getFeatureId())) {
            return CommonResult.validateFailed("自定义人群请选择人群");
        }
        if (6 == storeCouponRequest.getCrowd() && StringUtils.isBlank(storeCouponRequest.getPhones())) {
            return CommonResult.validateFailed("指定手机号客户请填写手机号");
        }
    	
        if(storeCouponService.saveEntity(storeCouponRequest)){
            return CommonResult.success();
        }else{
            return CommonResult.failed();
        }
    }
    
    /**
     * 分页
     * @author daigb
     * @date:  2022-01-17 14:53
     */
    @ApiOperation(value = "分页")
    @GetMapping(value = "/page")
    public CommonResult<CommonPage<StoreCoupon>> pageEntity(StoreCouponSearchRequest storeCouponSearchRequest, PageParamRequest pageParamRequest, HttpServletRequest request){
    	storeCouponSearchRequest.setMerId(getMerId(request));
    	CommonPage<StoreCoupon> storeCouponCommonPage = CommonPage.restPage(storeCouponService.pageEntity(storeCouponSearchRequest, pageParamRequest));
        return CommonResult.success(storeCouponCommonPage);
    }
    
    /**
     * 列表
     * @author daigb
     * @date:  2022-01-17 14:53
     */
    @ApiOperation(value = "列表")
    @GetMapping(value = "/list")
    public CommonResult<List<StoreCoupon>> listEntity(StoreCouponSearchRequest storeCouponSearchRequest, HttpServletRequest request){
    	storeCouponSearchRequest.setMerId(getMerId(request));
    	List<StoreCoupon> storeCouponCommons = storeCouponService.listEntity(storeCouponSearchRequest);
    	return CommonResult.success(storeCouponCommons);
    }

    /**
     * 启用禁用
     * @author daigb
     * @date:  2022-01-17 14:59
     */
    @ApiOperation(value = "启用禁用")
    @RequestMapping(value = "/is-enabled/{id}/update/{status}", method = RequestMethod.POST)
    public CommonResult<String> updateStatus(@ApiParam(value = "主键id", required = true) @PathVariable("id") Integer id, @ApiParam(value = "是否隐藏", required = true) @PathVariable("status") Boolean status, HttpServletRequest request){
        StoreCoupon storeCoupon = new StoreCoupon();
        storeCoupon.setId(id);
        storeCoupon.setMerId(getMerId(request));
        storeCoupon.setStatus(status);
        if(storeCouponService.updateById(storeCoupon)){
            return CommonResult.success();
        }else{
            return CommonResult.failed();
        }
    }
    
    /**
     * 通过id查询
     * @Description:  
     * @author daigb 
     * @param @param id
     * @param @return
     * @return CommonResult<Object>
     * @throws
     */
    @ApiOperation(value = "通过id获取")
    @GetMapping("/{id}")
    public CommonResult<Object> getEntity(@ApiParam(value = "主键id", required = true) @PathVariable("id") Integer id) {
        return CommonResult.success(storeCouponService.info(id));
    }

    @ApiOperation(value = "通过优惠券id 获取指定手机号客户 发放成功失败数")
    @GetMapping("/phone/{id}/{status}")
    public CommonResult<List<StoreCouponUserPhone>> getPhoneInfos(@PathVariable Integer id,@PathVariable Boolean status) {
        return CommonResult.success(storeCouponService.getPhoneInfos(id, status));
    }

}



